import { Magnifier } from "../../static/javascripts/fangda.js";
import { url } from "./config.js";
import { AddRightStairs } from "./rightStairs.js";
import { cookie } from "../../static/javascripts/cookie.js"
window.addEventListener("load", () => {
      let goodid = window.location.hash.split("=")[1]
      let _index = Math.floor(Math.random() * 4)
      class GoodDetail {
            constructor(_index, goodid) {
                  this.goodInfo = null;
                  this.goodId = goodid;
                  this._index = _index;
                  this.goodData = null;
                  this.checkId();
            }
            checkId() {
                  if (this.goodId === undefined || this.goodId === null || this.goodId === "") {
                        alert("数据错误请重试!")
                        location.href = `./active.html`
                  }
                  this.loadGoodInfo();
            }
            async loadGoodInfo() {
                  let res = await axios(url + "/goodDetail.json");
                  let res2 = await axios(url + "/activeData.json");
                  let res3 = await axios(url + "/ulikeAll.json");
                  let ulike = null;
                  res3.data.forEach(item => {
                        if (this.goodId in item) {
                              ulike = item;
                        }
                  })
                  let goodTextInfoArr = res2.data;
                  this.imgList = res.data[_index];
                  let indexI = 0;
                  let indexJ = 0;
                  for (let i = 0; i < goodTextInfoArr.length; i++) {
                        for (let j = 0; j < goodTextInfoArr[i].goodslist.length; j++) {
                              // console.log(goodTextInfoArr[i].goodslist[j].content.goodsId , this.goodId);
                              if (goodTextInfoArr[i].goodslist[j].content.goodsId === Number(this.goodId)) {
                                    indexI = i;
                                    indexJ = j;
                              }
                        }
                  }
                  let goodData = goodTextInfoArr[indexI].goodslist[indexJ].content;
                  this.goodData = goodTextInfoArr[indexI].goodslist[indexJ];
                  this.goodData = Object.assign(this.goodData, { id: `${goodData.goodsId}`, cont: 1 })
                  // console.log(this.goodData);
                  this.render(this.imgList, goodData, ulike);
            }
            render(imgList, goodData, ulike) {
                  let id = this.goodId
                  let bannerImgStr = ``;
                  imgList.bannerImgList.forEach(item => {
                        bannerImgStr += `<div class="swiper-slide" select="fasle"><img src="${item.imageUrl}" alt=""></div>`
                  });
                  let str = `
                        <!-- 放大镜模块 -->
                        <div class="magnifierModule">
                        <div class="magnifierBox">
                              <div class="original">
                                    <img src="${imgList.bannerImgList[0].imageUrl}" alt="">
                                    <div class="focusbox"></div>
                              </div>                              
                              <div class="magnifierImgBox">
                                    <img class="magnifierImgBox_bg" src="${imgList.bannerImgList[0].imageUrl}" alt="">
                              </div>
                        </div>
                        <div class="swiper-container">
                              <div class="swiper-wrapper">
                                   ${bannerImgStr}                             
                              </div>
                              <!-- 如果需要分页器 -->                                                            
                              <!-- 如果需要导航按钮 -->
                              <div class="swiper-button-prev"></div>
                              <div class="swiper-button-next"></div>                              
                              <!-- 如果需要滚动条 -->                              
                        </div>
                        </div>                        
                        <div class="goodTextInfo">
                        <div class="brandInfo">
                              <span class="brandCountryImg"><img src="${goodData.brand.countryImgUrl}" alt=""></span>
                              <span class="brandCountryNam">${goodData.brand.country}</span>
                              <span class="symbol">|</span>
                              <span class="brandName">${goodData.brand.shortName}</spanc>
                        </div>
                        <div class="goodTitle">
                              <p class="title">${goodData.title}</p>
                              <p class="goodDesc">${goodData.subTitle}</p>
                        </div>
                        <ul class="priceBox">
                              <li class="boxTitle">售价</li>
                              <li class="priceInfo">
                                    <span class="symbol">$</span>
                                    <span class="princeNum">${goodData.priceInfo.actualPrice}</span>
                              </li>
                        </ul>
                        <ul class="sizBox">
                              <li class="boxTitle">尺码</li>
                              <li class="size_item">
                                    <span class="sizeItem" size="xs">xs</span>
                                    <span class="sizeItem" size="s">xs</span>
                                    <span class="sizeItem" size="m">m</span>
                                    <span class="sizeItem" size="l">l</span>
                                    <span class="sizeItem" size="xl">xl</span>
                                    <span class="sizeItem" size="xxl">xxl</span>
                                    <span class="sizeItem" size="xxxl">xxl</span>
                              </li>
                        </ul>
                        <ul class="goodNum">
                              <li class="boxTitle">数量</li>
                              <li class="setNum">
                                    <span class="miuns">-</span>
                                    <input type="tex" name="" id="num" value="1">
                                    <span class="plus">+</span>
                              </li>
                        </ul>
                        <ul class="btns">
                              <li>立即购买</li>
                              <li>加入购物车</li>
                        </ul>
                        </div>`;
                  let ulikeStr = ``;
                  ulike[id].forEach(item => {
                        ulikeStr += `
                        <dl class="item">
                              <dt>
                              <img src="${item.imageUrl}" alt="">
                              </dt>
                              <dd>
                              <div class="title">
                                    ${item.title}
                              </div>
                              <div class="priceBox">
                                    <span>$${item.currentPrice}</span><br>
                                    <span>${item.commentsCount}人已评价</span>
                              </div>
                              </dd>
                        </dl> 
                        `;
                  })
                  $(".goodInfo").html(str);
                  $(".uLikeBox").append(ulikeStr);

                  this.bindEvent();
            }
            bindEvent() {
                  new Swiper('.swiper-container', {
                        navigation: {
                              nextEl: '.swiper-button-next',
                              prevEl: '.swiper-button-prev',

                        },
                        slidesPerView: 4,
                        spaceBetween: 30,
                  });
                  new Magnifier({
                        scale: 0.5,
                        magnifierBox: ".magnifierBox",
                        original: ".original",
                        focus: ".focusbox",
                        magnifierImgBox: ".magnifierImgBox",
                        magnifierImgBox_bg: ".magnifierImgBox_bg"
                  });
                  new AddRightStairs(".container ");
                  let _this = this;
                  $(".swiper-slide").on("click", function () {
                        _this.changeImg($(this));
                  })
                  $(".plus").on("click", function () {
                        _this.addNum($(this));
                  })
                  $(".miuns").on("click", function () {
                        _this.minuNum($(this));
                  })
                  $(".sizeItem").on("click", function () {
                        _this.chooseSize($(this));
                  })
                  $(".btns").find("li:last-child").on("click", function () {
                        _this.addShopCar($(this));
                  })
            }
            changeImg(ele) {
                  let src = ele.find("img").attr("src")
                  console.log($(".original").find("img"));
                  $(".original").find("img").attr("src", src);
                  $(".magnifierImgBox").find("img").attr("src", src);
                  if (ele.attr("select")) {
                        ele.removeAttr("select")
                  } else {
                        ele.attr("select", "true")
                        ele.siblings(".swiper-slide").removeAttr("select")
                  }
            }
            addNum(ele) {
                  let num = Number(ele.prev("input").val());
                  num++;
                  num = num >= 99 ? 99 : num;
                  num = num <= 0 ? 0 : num;
                  ele.prev("input").val(num);
            }
            minuNum(ele) {
                  let num = Number(ele.next("input").val());
                  num--;
                  num = num >= 99 ? 99 : num;
                  num = num <= 0 ? 0 : num;
                  ele.next("input").val(num);
            }
            chooseSize(ele) {
                  if (ele.attr("check")) {
                        ele.removeAttr("check")
                  } else {
                        ele.attr("check", "true")
                        ele.siblings(".sizeItem").removeAttr("check")
                  }
            }
            addShopCar() {
                  if (this.checkLogin()) {
                        let shopCarList = JSON.parse(localStorage.getItem("shopCat"));
                        shopCarList === null ? [] : shopCarList;
                        let _index = 0
                        // console.log(goods);
                        if (this.hasRepeat(this.goodData, shopCarList)) {
                              // console.log("有重复");
                              shopCarList[_index].cont++;
                              // console.warn(shopCarList[_index].cont)
                        }
                        if (!this.hasRepeat(this.goodData, shopCarList)) {
                              // console.log("没有重复");
                              shopCarList.push(this.goodData)
                        }
                        console.log("current->", shopCarList);
                        localStorage.setItem("shopCat", JSON.stringify(shopCarList));
                        alert("添加成功")
                  }
            }
            hasRepeat(goods, list) {
                  // console.log(shopCarList,goods);
                  let flag = false
                  for (let i = 0; i < list.length; i++) {
                        // console.log(shopCarList[i].Id,goods.Id);
                        if (list[i].Id === goods.Id) {
                              _index = i
                              flag = true
                              return true;
                        }
                  }
                  if (flag == false)
                        return false;
            }
            checkLogin() {
                  let TOKEN = cookie("TOKEN");
                  if (TOKEN === null || TOKEN === undefined || TOKEN === "") {
                        console.log(11);
                        $("#login").trigger("click");
                  } else {
                        return true;
                  }
            }
      }
      new GoodDetail(_index, goodid)
});